package com.itheima.servlet;

import com.itheima.domain.Student;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/findAll")
public class FindAllStudentsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把文件中的学生信息展示在 网页上把

        //中文乱码问题
        resp.setHeader("Content-Type", "text/html;charset=utf-8");
        //组织数据
        BufferedReader reader = new BufferedReader(new FileReader("G://stu.txt"));
        ArrayList<Student> list = new ArrayList<>();
        String s;
        while ((s = reader.readLine()) != null) {
            String[] studentInfo = s.split(",");
            Student student = new Student(studentInfo[0], Integer.parseInt(studentInfo[1]), Integer.parseInt(studentInfo[2]));
            list.add(student);
        }
        //存储到  请求域
        req.setAttribute("students",list);
        // 数据展示在  listStudent.jsp
        RequestDispatcher dispatcher = req.getRequestDispatcher("/listStudent.jsp");
        dispatcher.forward(req,resp);
        //释放资源
        reader.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
